<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .text {
            width: 200px;
            /* height: 80px; */
            background-color: skyblue;
        }

        textarea {
            border: 1px solid pink;
        }

        span {
            float: right;
        }

        .pl {
            background-color: white;
        }

        .css {
            background-color: pink;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <div class="text">
        <textarea name="" id="" placeholder="发友善的评论"></textarea>
        <button>发布</button>
        <p><span>0/200字数</span></p>
        <div class="pl">
        </div>
    </div>
</body>
<script>
    // 功能：输入评论，实时显示字数
    //1.获取textarea
    //2.设置input事件
    //3.获取textarea的value值长度
    //4.获取span
    //5.将value值赋值给span
    const text = document.querySelector('textarea');
    const span = document.querySelector('span');
    const p = document.querySelector('p');
    text.addEventListener('focus', function () {
        p.style.opacity = 1;
        console.log(111);
    })
    text.addEventListener('blur', function () {
        p.style.opacity = 0;
        console.log(111);
    })
    text.addEventListener('input', function () {
        let val = text.value.length;
        span.innerHTML = `${val}/200字数`;
    })
    //--------------------------------------
    //1.设置事件keyup
    //2.当事件对象key等于enter就发布
    //3.创建p，将内容赋值给p
    const pl = document.querySelector('.pl');
    console.log(pl);
    text.addEventListener('keyup', function (e) {
        // console.log(e);
        if (e.key === 'Enter' && text.value.trim() !== '') {
            // console.log('ddd');
            // 创建新元素
            let newElm = document.createElement('p');
            //将评论赋值给创建的p标签中
            newElm.innerHTML = text.value;
            newElm.classList.add('css');
            // 将创建的p标签添加到对应的盒子中
            pl.appendChild(newElm);
            //按完Enter复原span字数统计
            span.innerHTML = '0/200字数';

        } else {
            span.innerHTML = '0/200字数';
        }
        // 发布完删除在文本域中的评论
        text.value = '';

    })
</script>

</html>